from rest_framework.serializers import ModelSerializer  # 序列化器
from .models import *  # 导入所有的模型类
from rest_framework.fields import SerializerMethodField  # 自定义数据格式模块
from users.serializers import UserSerializer


# 班级的序列化器
class ClassesSerializer(ModelSerializer):  # 序列化器类

    memberDetail = SerializerMethodField()  # 自定义展示字段

    class Meta:
        model = Classes  # 转序列化器
        exclude = ['is_delete']  # 不想展示的字段

    def get_memberDetail(self, instance):  # Classes
        # 获取当前班级所有的用户表的数据，并序列化
        # 班级正向访问用户表all获取所有的数据
        members = UserSerializer(instance.member.all(), many=True).data
        for i in members:
            print(i)

        return {
            'teachers': [i['username'] for i in members if i['is_superuser'] or 1 in i['groups']],
            'students': [i['username'] for i in members if 2 in i['groups']]
        }


# 注册学生的序列化器
# 班级的序列化器
class CreateUserSerializer(ModelSerializer):  # 序列化器类
    class Meta:
        model = User  # 转序列化器
        fields = ['username', 'first_name', 'email']
        extra_kwargs = {
            'username': {'required': True},  # 唯一不重复
            'email': {'required': True},  # 唯一不重复
        }

